package control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.MiljoBoven;
import model.User;
import view.LoginPanel;
import view.MainFrame;

/**
 * Handles login data entered by the users.
 *
 * @author Kevin
 */
public class LoginPanelListener implements ActionListener {

    private final MainFrame view;
    private final MiljoBoven model;
    private final LoginPanel loginPanel;

    /**
     * Constructor for the class LoginPanelListener
     *
     * @param mainFrame The main view object
     * @param miljoBoven The main model object
     * @param loginPanel The panel this class listens to
     */
    public LoginPanelListener(MainFrame mainFrame, MiljoBoven miljoBoven, LoginPanel loginPanel) {

        this.view = mainFrame;
        this.model = miljoBoven;
        this.loginPanel = loginPanel;
    }

    /**
     * Verifies username and password entered by the user and displays the main
     * panel if OK, otherwise an error message is shown.
     *
     * @param userName entered username
     * @param password entered password
     */
    public void verifyUserAndPassword(String userName, String password) {
        if (Validator.validate(userName)
                && Validator.validate(password)
                && model.checkPassword(userName, password)) {
            model.setCurrentUser(userName);
            view.getMainPanel().setTableData(model.setTableRowData());
            if (model.getCurrentUser().getUserType() == User.Type.COORDINATOR) {
                view.getMainPanel().addNewCaseButton();
            }
            view.showMainPanel();
        } else {
            loginPanel.loginErrorMessage();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        String loginName = loginPanel.getUsername();
        String loginPassword = loginPanel.getPassword();

        verifyUserAndPassword(loginName, loginPassword);
        loginPanel.setPasswordField("");
    }
}